<template>
  <div class="taskAllocationUpdata">
    <a-modal
      title="修改指控车及导弹资源"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      width="980px"
      @cancel="handleCancel"
    >
      <a-tabs default-active-key="1" @change="callback" v-model="activeKey">
        <a-tab-pane :key="1" tab="指控车">
          <div v-if="activeKey == 1">
            <a-divider orientation="left">1.星指上/下行链路工作参数配置</a-divider>
            <a-form-model :model="form" :label-col="labelCol1" :wrapper-col="wrapperCol1">
              <!-- <a-row>
                <a-col :span="20">
                  <a-form-model-item label="指控车同步时隙起跳数配置">
                    <a-radio-group v-model="value2" @change="onChange1" button-style="solid">
                      <a-radio-button value="1"> 1 </a-radio-button>
                      <a-radio-button value="2"> 2 </a-radio-button>
                      <a-radio-button value="3"> 3 </a-radio-button>
                      <a-radio-button value="4"> 4 </a-radio-button>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="creatInstruct" type="primary" style="margin-left: 10px"> 配置</a-button>
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="creatInstruct" type="primary" style="margin-left: 10px"> 发送</a-button>
                  </a-form-model-item>
                </a-col>
              </a-row> -->
              <a-row>
                <a-col :span="20">
                  <a-form-model-item label="星指上行链路工作参数配置">
                    <a-input-number v-model="formUp.packageGridValue" :max="1920" />
                    <!-- <a-input v-model="formUp.packageGridValue"> </a-input> -->
                    <!-- <div>
                      <span :key="index" v-for="(i, index) in upLength">
                        <a-input
                          :maxLength="2"
                          style="width: 50px; margin-right: 10px"
                          v-model="formUp.Values[index]"
                          @change="
                            (val) => {
                              handleInput(val, formUp.Values)
                            }
                          "
                        ></a-input>
                      </span>
                      <div style="color: red; margin-top: 10px; position: absolute; z-index: 2" v-if="falseFlag">
                        请输入两位16进制数
                      </div>
                    </div> -->
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button
                      @click="handleValues('9-星指上行链路接收机变频器频点号')"
                      type="primary"
                      style="margin-left: 10px"
                    >
                      配置</a-button
                    >
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button
                      @click="handleSend('9星指上行链路变频器频点信息')"
                      type="primary"
                      style="margin-left: 10px"
                    >
                      发送</a-button
                    >
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="20">
                  <a-form-model-item label="星指下行链路工作参数配置">
                    <a-input-number v-model="form.packageGridValue" :max="1920" />
                    <!-- <div>
                      <span :key="index" v-for="(i, index) in length">
                        <a-input
                          :maxLength="2"
                          style="width: 50px; margin-right: 10px"
                          v-model="form.Values[index]"
                          @change="
                            (val) => {
                              handleInput(val, form.Values)
                            }
                          "
                        ></a-input>
                      </span>
                      <div style="color: red; margin-top: 10px; position: absolute; z-index: 2" v-if="falseFlag">
                        请输入两位16进制数
                      </div>
                    </div> -->
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button
                      @click="handleValues('8-星指下行链路接收机变频器频点号')"
                      type="primary"
                      style="margin-left: 10px"
                    >
                      配置</a-button
                    >
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button
                      @click="handleSend('8星指下行链路变频器频点信息')"
                      type="primary"
                      style="margin-left: 10px"
                    >
                      发送</a-button
                    >
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="20">
                  <a-form-model-item label="指控车资源配置">
                    <a-checkbox-group @change="onChange" defaultChecked="">
                      <a-form-model-item label="同步时隙起跳数">
                        <a-radio-group v-model="value2" @change="onChange1" button-style="solid">
                          <a-radio-button value="1"> 1 </a-radio-button>
                          <a-radio-button value="2"> 2 </a-radio-button>
                          <a-radio-button value="3"> 3 </a-radio-button>
                          <a-radio-button value="4"> 4 </a-radio-button>
                        </a-radio-group>
                      </a-form-model-item>
                      <a-row>
                        <pool1 ref="pool1" :group="true" :data="JSON.stringify(poolData)" :small="2" />
                      </a-row>
                    </a-checkbox-group>
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="handleValues('6-分配给车1的时隙号')" type="primary" style="margin-left: 10px">
                      配置</a-button
                    >
                    <!-- <a-button @click="savePool" type="primary" style="margin-left: 10px"> 配置</a-button> -->
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="handleSend('6指挥车时隙分配信息')" type="primary" style="margin-left: 10px">
                      发送</a-button
                    >
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </a-tab-pane>
        <a-tab-pane :key="2" tab="导弹" force-render>
          <div v-if="activeKey == 2">
            <a-divider orientation="left">2.星弹工作参数配置</a-divider>
            <a-form-model :model="form1" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-row>
                <a-col :span="20">
                  <a-form-model-item label="星弹上行链路工作参数配置">
                    <a-input v-model="form.region" placeholder="请输入信道号（可以连续，用,号区分）"></a-input>
                    <pool1
                      ref="pool"
                      :total="1920"
                      :small="3"
                      style="width: 100%; height: 250px; overflow-y: auto; padding: 3px"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="ballConfig('4-信道')" type="primary" style="margin-left: 10px"> 配置</a-button>
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="handleSend('4信道授权信息')" type="primary" style="margin-left: 10px">
                      发送</a-button
                    >
                  </a-form-model-item>
                </a-col>
              </a-row>
              <!-- <a-row>
                <a-col :span="20">
                  <a-form-model-item label="星弹下行链路工作参数配置">
                    <a-select v-model="form1.speed" placeholder="请选择">
                      <a-select-option value="32kbps"> 32kbps </a-select-option>
                      <a-select-option value="96kbps"> 96kbps </a-select-option>
                      <a-select-option value="256kbps"> 256kbps </a-select-option>
                      <a-select-option value="1024kbps"> 1024kbps </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="creatInstruct" type="primary" style="margin-left: 10px"> 配置</a-button>
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <a-form-model-item>
                    <a-button @click="creatInstruct" type="primary" style="margin-left: 10px"> 发送</a-button>
                  </a-form-model-item>
                </a-col>
              </a-row> -->
            </a-form-model>
          </div>
        </a-tab-pane>
      </a-tabs>
      <selectChannel ref="selectChannel" />
    </a-modal>
  </div>
</template>

<script>
import selectChannel from './selectChannel.vue'
import { getAction, httpAction } from '@/api/manage.js'
import pool from './resourcePool.vue'
import pool1 from './resourcePool1.vue'
import { Turns, hex2int } from '@/utils/util.js'
export default {
  components: {
    pool,
    pool1,
    selectChannel,
  },
  data() {
    return {
      value2: '',
      visible: false,
      subData: [],
      activeKey: 1,
      tabActiveKey: 1,
      confirmLoading: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      labelCol1: { span: 8 },
      wrapperCol1: { span: 16 },
      form: { Values: [], packageGridValue: '' },
      form1: {},
      formUp: { Values: [], packageGridValue: '' },
      formBall: {},
      resourcesForm: {},
      resourcesList: [],
      resourcesNo: {},
      falseFlag: false,
      length: 2,
      upLength: 2,
      poolData: [],
      group: true,
      url: {
        getNmcPackageGridValueByCode: '/grid/nmcPackageGridValue/code',
        nmcPackageGridList: '/grid/nmcPackageGrid/list',
        addnmcPackageGridValue: '/grid/nmcPackageGridValue/add', //{"packageGridValue":"22AA","Values":["22","aa"],"packageGridId":"1663806762680139777"}
      },
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.activeKey = 1
        for (let i = 0; i < 30; i++) {
          this.resourcesList.push({ label: i, status: 1, disabled: false, active: '' })
        }
        this.getValueByCode()
      }
    },
    activeKey(val) {
      if (val == 1) {
        this.getValueByCode()
      } else {
        this.getValueByCodeBall()
      }
    },
  },

  activated() {
    for (let i = 1; i <= 30; i++) {
      this.poolData.push({ id: i, check: false })
    }
  },
  methods: {
    ballConfig(val) {
      let act = this.$refs.pool.subData.filter((i) => i.check == true)
      let str = ''
      act.forEach((i, index) => {
        str += i.id.toString(16).padStart(4, 0).toUpperCase()
      })
      if (val == '4-信道') {
        this.formBall.packageGridValue = str.toUpperCase()
        httpAction(this.url.addnmcPackageGridValue, this.formBall, 'post').then((res) => {
          this.visibleAdd = false
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    //发送事件
    handleSend(val) {
      let temp = { packageCode: val }
      this.$refs.selectChannel.showModal(temp)
    },
    sendInstruct() {},
    // 工程量值根据Code回显
    getValueByCode() {
      // let url = escape(` ${this.url.getNmcPackageGridValueByCode}/'8-星指下行链路接收机变频器频点号'`)
      // getAction(url).then((res) => {
      getAction(`${this.url.getNmcPackageGridValueByCode}/${encodeURI('8-星指下行链路接收机变频器频点号')}`).then(
        (res) => {
          let temp = res.result
          this.form.packageGridId = '8-星指下行链路接收机变频器频点号'
          this.length = temp.packageGrid.gridStaticLength
          this.form.packageGridValue = hex2int(temp.packageGridValue)
          // this.$set(this.form, 'Values', [...this.StringToArr(temp.packageGridValue)])
        }
      )
      getAction(`${this.url.getNmcPackageGridValueByCode}/${encodeURI('9-星指上行链路接收机变频器频点号')}`).then(
        (res) => {
          let temp = res.result
          this.formUp.packageGridId = '9-星指上行链路接收机变频器频点号'
          this.upLength = temp.packageGrid.gridStaticLength
          this.formUp.packageGridValue = hex2int(temp.packageGridValue) < 1921 ? hex2int(temp.packageGridValue) : '0'
          console.log(temp.packageGridValue, hex2int(temp.packageGridValue))
          // this.$set(this.formUp, 'Values', [...this.StringToArr(temp.packageGridValue)])
        }
      )
      getAction(`${this.url.getNmcPackageGridValueByCode}/${encodeURI('6-分配给车1的时隙号')}`).then((res) => {
        let temp = res.result
        this.resourcesForm.packageGridId = '6-分配给车1的时隙号'
        let tempData = temp.packageGridValue.slice(-8)
        let data = Turns(tempData, 2).split('')
        let Arr = []
        data.forEach((item, index) => {
          Arr.push({
            id: data.length - index,
            check: item == 0 ? true : false, //可用是1，否是0
          })
        })
        Arr.shift()
        Arr.shift()
        let end = [...Arr.reverse()]
        this.$refs.pool1.subData = JSON.parse(JSON.stringify(end))
      })
      // getAction(`${this.url.getNmcPackageGridValueByCode}/${encodeURI('6-分配给指挥车1的时隙个数')}`).then((res) => {
      //   let temp = res.result
      //   this.resourcesNo.packageGridId = '6-分配给指挥车1的时隙个数'
      //   this.resourcesNo.No = res.result.packageGridValue
      // })
    },
    getValueByCodeBall() {
      getAction(`${this.url.getNmcPackageGridValueByCode}/${encodeURI('4-信道')}`).then((res) => {
        let temp = res.result
        this.formBall.packageGridId = '4-信道'
        let tempData = Turns(temp.packageGridValue, 4)
        tempData.forEach((i) => {
          this.$refs.pool.subData.find((item) => item.id == i).check = true
        })
        console.log(tempData, 'Turns(tempData, 4)')
        // this.$refs.pool1.subData = JSON.parse(JSON.stringify(end))
        // this.upLength = temp.packageGrid.gridStaticLength
        // this.$set(this.formUp, 'Values', [...this.StringToArr(temp.packageGridValue)])
      })
    },
    hex2int(hex) {
      //16进制转10进制
      var len = hex.length,
        a = new Array(len),
        code
      for (var i = 0; i < len; i++) {
        code = hex.charCodeAt(i)
        if (48 <= code && code < 58) {
          code -= 48
        } else {
          code = (code & 0xdf) - 65 + 10
        }
        a[i] = code
      }
      return a.reduce(function (acc, c) {
        acc = 16 * acc + c
        return acc
      }, 0)
    },
    StringToArr(str) {
      var list = []
      var ar2 = 0
      for (let i = 0; i < str.length - 1; i += 2) {
        list.push(str.substring(i, i + 2))
      }
      return list
    },
    onSubmit() {
      console.log(this.form)
    },
    handleValues(val) {
      if (val == '8-星指下行链路接收机变频器频点号') {
        // this.form.packageGridValue = this.form.Values.join('').toUpperCase()
        this.form.packageGridValue = this.form.packageGridValue.toString(16).padStart(4, 0)
        httpAction(this.url.addnmcPackageGridValue, this.form, 'post').then((res) => {
          this.visibleAdd = false
          if (res.success) {
            this.getValueByCode()
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })
      } else if (val == '9-星指上行链路接收机变频器频点号') {
        this.formUp.packageGridValue = this.formUp.packageGridValue.toString(16).padStart(4, 0)
        // this.formUp.packageGridValue = this.formUp.Values.join('').toUpperCase()
        httpAction(this.url.addnmcPackageGridValue, this.formUp, 'post').then((res) => {
          this.visibleAdd = false
          if (res.success) {
            this.getValueByCode()
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })
      } else if (val == '6-分配给车1的时隙号') {
        let subData = this.reverseAndConvert(this.$refs.pool1.subData)
        let str = ''
        subData.forEach((i) => {
          str += i.data
        })
        let strs = str.padStart(62, 1).padStart(64, 0)
        let temp = Turns(strs, 16) //6-分配给车1的时隙号
        this.resourcesForm.packageGridValue = temp
        httpAction(this.url.addnmcPackageGridValue, this.resourcesForm, 'post').then((res) => {
          this.visibleAdd = false
          if (res.success) {
            this.getValueByCode()
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })

        this.resourcesNo.packageGridId = '6-分配给指挥车1的时隙个数'
        console.log(this.$refs.pool1.checkGroup)
        this.resourcesNo.packageGridValue = this.$refs.pool1.checkGroup.length.toString(16).padStart(4, 0).toUpperCase() //分配的数值
        console.log(this.resourcesNo, 'this.resourcesNo')
        // return
        httpAction(this.url.addnmcPackageGridValue, this.resourcesNo, 'post').then((res) => {
          this.visibleAdd = false
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    savePool() {
      let subData = this.reverseAndConvert(this.$refs.pool1.subData)
      let str = ''
      subData.forEach((i) => {
        str += i.data
      })
      let strs = str.padStart(62, 1).padStart(64, 0) //补位0和1
      let temp = Turns(strs, 16) //6-分配给车1的时隙号
    },
    Turns(str, type) {
      if (type == 16) {
        //8位二进制数转2位十六进制数
        let d = []
        let c = str
        for (let i = 0; i < c.length; i += 8) {
          d.push(c.slice(i, i + 8))
        }
        let items = ''
        d.forEach((item) => {
          // 把num当做2进制的值 转换为10进制
          item = JSON.parse(JSON.stringify(parseInt(item, 2).toString(16))).padStart(2, 0)
          items += item
        })
        return items.toUpperCase()
      } else if (type == 2) {
        //十六进制转8位二进制数
        let d = []
        let c = str
        for (let i = 0; i < c.length; i += 2) {
          d.push(c.slice(i, i + 2))
        }
        let items = ''
        d.forEach((item) => {
          item = JSON.parse(JSON.stringify(parseInt(item, 16).toString(2))).padStart(8, 0)
          items += item
        })
        return items
      } else if (type == 4) {
        let d = []
        let c = str
        for (let i = 0; i < c.length; i += 4) {
          d.push(c.slice(i, i + 4))
        }
        let items = []
        d.forEach((item) => {
          item = hex2int(item)
          console.log(item, '2525')
          // item = JSON.parse(JSON.stringify(parseInt(item, 16).toString(2))).padStart(8, 0)
          items.push(item)
        })
        return items
      }
    },
    // 逆序，选择状态转换成0/1
    reverseAndConvert(subData) {
      var newArray = [] //新建的空数组是为了保存翻转后的数组的
      for (var i = 0; i < subData.length; i++) {
        if (subData[i].check) {
          subData[i].data = 0
        } else {
          subData[i].data = 1
        }
        subData[i].id = i + 1
        newArray.unshift(subData[i]) //利用unshift 将原数组重新插入newArray[]数组中
      }
      console.log(newArray, 'newArray')
      return newArray
    },
    onChange(e) {
      this.resourcesList.forEach((i) => {
        if (i.active == this.tabActiveKey) {
          i.disabled = false
        }
        e.forEach((item) => {
          if (i.label == item) {
            i.disabled = true
            i.active = this.tabActiveKey
          }
        })
      })
    },
    onChange1() {},
    creatInstruct() {},
    callback(key) {
      console.log(key)
    },
    getnmcPackageGridList() {
      // 8-星指下行链路接收机变频器频点号
      getAction(this.url.nmcPackageGridList, { pageSize: -1 }).then((res) => {
        this.nmcPackageGridList = res.result.records
        let temp = this.nmcPackageGridList.find((i) => i.gridCode == '8-星指下行链路接收机变频器频点号')
        this.form.packageGridId = temp.gridCode
        this.length = temp.gridStaticLength
      })
    },
    handleInput(e, record) {
      this.falseFlag = false
      let val = e.target.value
      let reg = /^[A-Fa-f0-9]{2}$/
      if (!reg.test(val)) {
        this.falseFlag = true
        return false
      }
      record.forEach((e) => {
        if (!reg.test(e)) {
          this.falseFlag = true
          return false
        }
      })
    },
    showModal(record) {
      console.log(record)
      this.visible = true
      // this.getnmcPackageGridList()
    },
    handleOk(e) {
      this.confirmLoading = true
      console.log(this.dataSource)
      //调新增接口
      this.$emit('ok', this.dataSource)
      setTimeout(() => {
        this.visible = false
        this.confirmLoading = false
      }, 2000)
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
    },
  },
}
</script>

<style lang="less" scoped>
.taskAllocationUpdata {
  .ant-checkbox-group {
    // height: 300px;
    // line-height: 0.9;
    .ant-checkbox-wrapper {
      margin: 0;
    }
    .ant-col {
      width: auto;
      margin: 0;
    }
  }
}
.tabs .ant-row {
  width: 600px;
  .ant-checkbox-inner {
    width: 40px !important;
    height: 40px !important;
    text-align: center;
    &::after {
      width: 7px;
      height: 14px;
      left: 35%;
    }
  }
}
.ant-checkbox-inner {
  /* background-color: red !important; */
  border-color: #6e6e6e !important;
}
</style>
